<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :width="state.width + 'px'" @close="handleClose"
    :maskClosable="false" destroyOnClose :title="getTitle" @ok="handleSubmit" :defaultFullscreen="true" showFooter>

    <a-tabs v-model:activeKey="activeKey" @change="handleTabChange" class="tab">
      <a-tab-pane key="templateVar" tab="变量定义" force-render>
        <TemplateVar ref="templateVarRel" v-model:varData="templateConfig.varData" :taskId="state.record.taskId" />
      </a-tab-pane>

      <a-tab-pane key="templateConfig" tab="模板配置" force-render>
        <BasicForm @register="registerForm">
        </BasicForm>
        <a-row class="template-content" v-show="state.isShowEdit">
          <a-col :sm="20" :md="20" :lg="20" :xl="20">
            <div style="margin-left: 12px; margin-right: 20px;">
              <MyAceEditor ref="editorRef" v-model:content="templateConfig.content" model="text"
                :style="aceEditorStyle" />
            </div>
          </a-col>
          <a-col :sm="4" :md="4" :lg="4" :xl="4" style="margin-top: 5px">
            <div :class="{ 'hasFix': true }" style="font-size: 14px;">
              <a-tooltip placement="leftTop">
                <template #title>
                  <span>点击变量直接插入</span>
                </template>
                <h4 style="margin: 5px 0">
                  模板变量
                </h4>
              </a-tooltip>
              <template v-for="{ key, desc } in templateConfig.varData" :key="key">
                <div class="velocity-var">
                  <a @click="handleExpressionClick(`$` + `{` + key + '}')">{{ desc }}</a>
                </div>
              </template>
            </div>
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, reactive, ref} from 'vue';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import MyAceEditor from '/@/components/My/MyAceEditor.vue';
import TemplateVar from './TemplateVar.vue';
import {useMessage} from "/@/hooks/web/useMessage";
import {templateSchema} from '../template.data';
import {getTemplate, saveOrUpdateTemplate} from '../template.api';
import {ChannelTypeEnum} from '../template.model';
import {BasicForm, useForm} from '/@/components/Form/index';
import {useSelectMaterial} from '/@/components/BizMaterial/index'

useSelectMaterial()

const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);

const templateVarRel = ref()
const activeKey = ref('templateVar')
const editorRef = ref()
const templateConfig = ref<any>({
  content: '',
  varData: []
})
const state = reactive<any>({
  width: 750,
  // 是否展示编辑器
  isShowEdit: false,
  record: {},
  labelCol: {}
})

const aceEditorStyle = ref<String>("width: 100%; height: calc(100vh - 200px)")

//表单配置
const [registerForm, { resetFields, setFieldsValue, validate, updateSchema, setProps }] = useForm({
  schemas: templateSchema,
  showActionButtonGroup: false,
  labelCol: {
    md: { span: 2 },
    sm: { span: 2 },
  },
  wrapperCol: {
    md: { span: 19 },
    sm: { span: 19 },
  },
});


const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  state.record = await getTemplate({ id: data.record.id })
  console.log('record', state.record);

  const template = state.record.templateConfig ? JSON.parse(state.record.templateConfig) : []
  const tempVarData: any = []

  for (var key in template?.varData) {
    const fieldData = template?.varData[key]
    fieldData.fieldName = key
    tempVarData.push(fieldData)
  }

  template.varData = tempVarData
  templateConfig.value = template;

  const channelType = state.record.channelType
  if (channelType === ChannelTypeEnum.WX_MA ||
    channelType === ChannelTypeEnum.WX_MP) {
    state.width = 800
    state.isShowEdit = true
    state.labelCol = {
      labelCol: {
        md: { span: 3 },
        sm: { span: 3 },
      }
    }
  } else if (channelType === ChannelTypeEnum.EMAIL ||
    channelType === ChannelTypeEnum.SMS ||
    channelType === ChannelTypeEnum.PC ||
    channelType === ChannelTypeEnum.APP) {
    state.width = 960
    state.isShowEdit = true
    state.labelCol = {
      labelCol: {
        md: { span: 2 },
        sm: { span: 2 },
      }
    }
  } else {
    state.isShowEdit = false
    state.labelCol = {
      labelCol: {
        md: { span: 3 },
        sm: { span: 3 },
      }
    }
  }

  setProps(state.labelCol)

  editorRef.value.updateEditor({
    readOnly: false, value: templateConfig.value.content
  })

  //表单赋值
  await setFieldsValue({
    ...state.record, ...templateConfig.value
  });


  console.log("data: ", data.record, 'templateConfig', templateConfig.value)
});
//设置标题
const getTitle = computed(() => {
  return `编辑 ${state.record.taskName}-${state.record.channelTypeName} 模板内容`
});

const handleExpressionClick = (expression) => {
  if (expression) {
    console.log("expression: ", expression)
    editorRef.value.insert(expression)
  }
}

//表单提交事件
async function handleSubmit() {
  setDrawerProps({ confirmLoading: true });
  try {
    const templateForm = await validate()

    // 构造变量数据
    const varData = {}

    // 删除模板变量其他无用参数并钩爪请求参数
    templateConfig.value.varData.forEach(e => {
      const fieldName = e.fieldName
      delete e.updatedBy
      delete e.updatedAt
      delete e.createdBy
      delete e.createdAt
      delete e.id
      delete e.taskId
      delete e.fieldName
      varData[fieldName] = e
    })

    const form = {
      ...state.record,
      templateConfig: JSON.stringify({ ...templateConfig.value, ...templateForm, varData })
    }
    console.log("form: ", form);
    await saveOrUpdateTemplate(form, form.id)
    //关闭弹窗
    closeDrawer();
    createMessage.success(`编辑模板成功`)
    //刷新列表
    emit('success');
    editorRef.value && editorRef.value.reset()
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

const handleClose = (e) => {

}

const handleTabChange = async (key) => {
  activeKey.value = key;
}

</script>

<style lang="less">
.template-content {
  margin-top: 10px;
}

span.split {
  color: #ccc;
  margin: 0 3px;
}

.hasFix {
  /* position: fixed; */
  position: absolute;
  overflow-y: auto;
  top: 10px;
  bottom: 0px;
}

.velocity-var li {
  font-size: 14px;
  color: #606266;
  line-height: 26px;
}

.velocity-var a {
  color: #409EFF;
  display: inline;
  /* font-weight: 500; */
}

.velocity-var a:hover {
  color: rgba(64, 158, 255, 0.75);
}

.velocity-var-container {
  overflow-y: auto
}</style>
